//author: Patrick GRamsl -ITM12

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, char * argv[]) {

	//Check if the number of Parameters is correct
	if (argc != 3) {
        fprintf(stderr,"Please check the number of Parameters\nusage: ./yacp <source> <target>\n");
        return 1;
    }

    char* source = argv[1];
    char* target = argv[2];

    /*
		Used to create the file and check that the file can be created and does not exist
		Int Variable Typw because open gives a nummeric Value of its return status
    */
    int target_return = open(target, O_WRONLY | O_CREAT | O_EXCL, 0755);

    //Errors opening the file are handled here
    if(target_return < 0)
    {
    	fprintf(stderr, "yacp could not create your file %s\nPlease make sure that the files does not exist\n", target);
    	fprintf(stderr, "The error was %s\n", strerror(errno));
    	//remove(target_file);
    	return errno;
    }

    //If we can open the file we open the source file as "Read Only" and check if opening works
    int source_return = open(source, O_RDONLY);

    //Here is the check
    if (source_return < 0)
    {
    	fprintf(stderr, "yacp encountered an error with your source file%s\nPlease check that you have permission to open it and that it exists\n", strerror(errno));
		fprintf(stderr, "The error was %s\n", strerror(errno));
		//remove(target_file);
		return errno;
    }

   	//create a buffer to copy the source file to the destination file
   	char buffer[1];

   	//bevore we can start we need to more variables to save the return value
   	int read_return;
   	int write_return;

   	//Now to the fun part
   	do
   	{
   		//First lets read our file and save the return value in case something goes wrong
   		read_return = read(source_return, &buffer, 1);

   		//In case something goes wrong
   		if(read_return < 0)
   		{
   			fprintf(stderr, "yacp encountered an error while reading!%s\nPlease make sure that the source is still accessible\n", strerror(errno));
   			fprintf(stderr, "The error was %s\n", strerror(errno));
   			//remove(target_file);
   			return errno;
   		}

   		//Now lets write to our target file
   		write_return = write(target_return, &buffer, 1);

   		//And once again a check if everything goes smoothly
   		if(write_return < 0)
   		{
   			fprintf(stderr, "yacp encountered an error while writing!%s\nPlease make sure that the target is still accessible\n", strerror(errno));
   			fprintf(stderr, "The error was %s\n", strerror(errno));
   			//remove(target_file);
   			return errno;
   		}
   	}while(read_return);

   	//Lets end the Programm
   	return 0;
}
